/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014-2017 abel533@gmail.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package net.quanter.shield.mybatis.pagehelper;

import com.github.pagehelper.Page;
import com.github.pagehelper.dialect.AbstractHelperDialect;
import com.github.pagehelper.util.MetaObjectUtil;
import javax.persistence.Id;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.mapping.*;
import org.apache.ibatis.reflection.MetaObject;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 支持cache数据库的分页
 *
 * @author 王老实
 * @since 1.3.12.RELEASE
 */
public class CacheDialect extends AbstractHelperDialect {

    ThreadLocal<String> currentIdColumnName = new ThreadLocal<>();
    @Override
    public Object processPageParameter(MappedStatement ms, Map<String, Object> paramMap, Page page, BoundSql boundSql, CacheKey pageKey) {
        if (page.getStartRow() > 0) {
            Collection<ResultMap> resultMaps = ms.getResultMaps();
            String id = null;
            for (ResultMap resultMap : resultMaps) {
                List<ResultMapping> resultMappingList = resultMap.getIdResultMappings();
                if (resultMappingList.isEmpty()) {
                    Class resultClass = resultMap.getType();
                    Field[] fields = resultClass.getDeclaredFields();
                    for (Field field : fields) {
                        boolean oldAccessible = field.canAccess(resultMap);
                        field.setAccessible(true);
                        Annotation annotation = field.getAnnotation(Id.class);
                        if (annotation != null) {
                            id = field.getName();
                        }
                        field.setAccessible(oldAccessible);
                        if (id != null) {
                            break;
                        }
                    }
                } else {
                    id = resultMappingList.get(0).getColumn();
                }
            }
            if (id == null) {
                id = "id";
            }
            currentIdColumnName.set(id);
            int param_old_size = boundSql.getParameterMappings().size();
            List<ParameterMapping> newParameterMappings = new ArrayList<>(boundSql.getParameterMappings());

            for (int i = 0; i < param_old_size; i++) {
                ParameterMapping parameterMapping = boundSql.getParameterMappings().get(i);
                String key = "param" + (i + 1);
                Object value = paramMap.get(key);
                paramMap.put("param" + (param_old_size + i + 1), value);
                pageKey.update(value);
                newParameterMappings.add(
                    new ParameterMapping.Builder(ms.getConfiguration(), parameterMapping.getProperty(), parameterMapping.getTypeHandler()).build());
            }
            MetaObject metaObject = MetaObjectUtil.forObject(boundSql);
            metaObject.setValue("parameterMappings", newParameterMappings);

        }
        return paramMap;
    }

    @Override
    public String getPageSql(String sql, Page page, CacheKey pageKey) {
        if (page.getStartRow() == 0) {
            return String.format("select top %d * from (%s) a", page.getPageSize(), sql);
        } else {
            String id_columns = currentIdColumnName.get();
            currentIdColumnName.remove();
            return String.format("select top %d * from (%s) a where a.%s not in (select top %d %s from (%s) b)",
                page.getPageSize(), sql, id_columns, page.getStartRow(), id_columns, sql);
        }
    }

}
